package net.facelib.live;

import static net.gdface.sdk.SDKLog.SDK_LOGGER;

import java.util.HashMap;
import java.util.Iterator;
import java.util.ServiceLoader;
import com.google.common.base.Strings;

/**
 * 活体检测工具类<br>
 * @author guyadong
 *
 */
class BaseFaceLiveSupport{
	private BaseFaceLiveSupport() {
	}

	/**
	 * 应用层提供的{@link FaceLive}接口实例,未提供则值为{@code null}
	 */
	static final HashMap<String, FaceLive> liveInstances;
	static FaceLive INSTANCE;
	/**
	 * SPI(Service Provider Interface)机制加载 {@link FaceLive}实例,没有找到返回空map
	 */
	private static HashMap<String, FaceLive> loadFaceLive() {		
		ServiceLoader<FaceLive> loader = ServiceLoader.load(FaceLive.class);
		HashMap<String, FaceLive> instances = new HashMap<>();
		for(Iterator<FaceLive> itor = loader.iterator();itor.hasNext();){
			try {
				FaceLive facelive = itor.next();
				SDK_LOGGER.log("found FaceLive instance {}",facelive);
				String productId = facelive.getProductID();
				if(!Strings.isNullOrEmpty(productId)){					
					SDK_LOGGER.log("quality instance {}",facelive);
					instances.put(productId, facelive);
				}
			} catch (ExceptionInInitializerError e) {
				SDK_LOGGER.log("{}:{}",e.getClass().getName(),e.getMessage());
				if(null != e.getCause()){
					SDK_LOGGER.logTrace(true, e.getCause());
				}else{
					SDK_LOGGER.logTrace(true, e);
				}
			}catch (Throwable e) {
				SDK_LOGGER.log("{}:{}",e.getClass().getName(),e.getMessage());
				SDK_LOGGER.logTrace(true, e);
			}
		}
		return instances;
	}
	static{
		liveInstances = loadFaceLive();
		if(!liveInstances.isEmpty()){
			// 初始化默认实例
			INSTANCE = liveInstances.values().iterator().next();
		}
	}
}
